#define _CRT_SECURE_NO_WARNINGS 1

#include "SList.h"

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* node = (SListNode*)malloc(sizeof(SListNode));
	if (node == NULL)
	{
		printf("malloc error!\n");
		return NULL;
	}
	node->data = x;
	node->next = NULL;
	return node;
}

void SListPrint(SListNode* plist)
{
	SListNode* phead = plist;
	while (phead != NULL)
	{
		printf("%d->", phead->data);
		phead = phead->next;
	}
	printf("NULL\n");
}

void SListPushBack(SListNode** pplist, SLTDateType x)
{
	SListNode* pend = *pplist;
	if (pend == NULL)
	{
		SListNode* node = BuySListNode(x);
		*pplist = node;
		return;
	}
	while (pend->next != NULL)
	{
		pend = pend->next;
	}
	SListNode* node = BuySListNode(x);
	pend->next = node;
}

void SListPushFront(SListNode** pplist, SLTDateType x)
{
	SListNode* node = BuySListNode(x);
	node->next = *pplist;
	*pplist = node;
}

void SListPopBack(SListNode** pplist)
{
	SListNode* pend = *pplist;
	if (pend == NULL)
	{
		printf("nothing to popback\n");
		return;
	}
	else if (pend->next == NULL)
	{
		free(pend);
		*pplist = NULL;
		return;
	}
	while (pend->next->next != NULL)
	{
		pend = pend->next;
	}
	free(pend->next);
	pend->next = NULL;
}

void SListPopFront(SListNode** pplist)
{
	SListNode* phead = *pplist;
	if (phead == NULL)
	{
		printf("nothing to popback\n");
		return;
	}
	*pplist = (*pplist)->next;
	free(phead);
	phead = NULL;
}


SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	SListNode* phead = plist;
	while (phead != NULL)
	{
		if (phead->data == x)
		{
			return phead;
		}
		phead = phead->next;
	}
	return NULL;
}

void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos);
	SListNode* node = BuySListNode(x);
	node->next = pos->next;
	pos->next = node;
}

void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	SListNode* pend = pos->next;
	if (pend == NULL)
	{
		printf("Nothing to erase\n");
		return;
	}
	pos->next = pend->next;
	free(pend);
	pend = NULL;
}

void SListDestroy(SListNode* plist)
{
	SListNode* pend = plist;
	while (pend != NULL)
	{
		plist = plist->next;
		free(pend);
		pend = plist;
	}
}

